package com.xxh.securitydemo.filter;

import com.xxh.securitydemo.compoent.DynamicAccessDecisionManager;
import com.xxh.securitydemo.compoent.DynamicSercurityMetaDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 动态权限过滤器，用于实现基于路径的动态权限过滤
 */
@ConditionalOnBean(name = "dynamicSecurityService")
@Component
public class DynamicSecurityFilter extends AbstractSecurityInterceptor implements Filter {

    @Autowired
    DynamicSercurityMetaDataSource dynamicSercurityMetaDataSource;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request=(HttpServletRequest)servletRequest;
        FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain);
        if(request.getMethod().equals(HttpMethod.OPTIONS)){
            fi.getChain().doFilter(fi.getRequest(),fi.getResponse());
            return;
        }

        //此处会调用AccessDecisionManager中的decide方法进行鉴权操作
        InterceptorStatusToken token = super.beforeInvocation(fi);
        try {
            fi.getChain().doFilter(fi.getRequest(),fi.getResponse());
        }finally {
            super.afterInvocation(token,null);
        }
    }

    @Autowired
    public void setAccessDecisionManager(DynamicAccessDecisionManager decisionManager) {
        super.setAccessDecisionManager(decisionManager);
    }

    @Override
    public Class<?> getSecureObjectClass() {
        return FilterInvocation.class;
    }

    @Override
    public void destroy() {

    }

    //定义权限判定的数据源
    @Override
    public SecurityMetadataSource obtainSecurityMetadataSource() {
        return dynamicSercurityMetaDataSource;
    }
}
